<template>
  <el-card>
    <el-form :model="roleInfo" ref="roleForm">
      <el-form-item label="角色名称" :label-width="formLabelWidth">
        <el-input v-model="roleInfo.rolename" autocomplete="off"></el-input>
      </el-form-item>
      <el-form-item label="权限" :label-width="formLabelWidth">
        <el-tree
          :data="data"
          show-checkbox
          node-key="id"
          default-expand-all
          :default-checked-keys="roleInfo.memus"
          :props="defaultProps"
          ref="tree"
        ></el-tree>
      </el-form-item>
      <el-form-item label="状态" :label-width="formLabelWidth">
        <el-radio-group v-model="roleInfo.status">
          <el-radio :label="1">启用</el-radio>
          <el-radio :label="2">禁用</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item :label-width="formLabelWidth">
        <el-button type="primary" @click="submitForm('roleForm')">确认修改</el-button>
      </el-form-item>
    </el-form>
  </el-card>
</template>

<script>
export default {
  data() {
    return {
      roleId: this.$route.params.id,
      dialogTableVisible: false,
      dialogFormVisible: false,
      roleInfo: {
        rolename: "",
        menus: []
      },
      formLabelWidth: "120px",
      data: [],
      defaultProps: {
        children: "children",
        label: "title"
      }
    };
  },
  methods: {
    // 获取属性菜单
    getMenuTree() {
      this.$http.get("/api/menulist?istree=1").then(res => {
        if (res.code == 200) {
          this.data = res.list;
        }
      });
    },
    // 获取角色信息
    getRoleInfo() {
      this.$http.get(`./api/roleinfo?id=${this.roleId}`).then(res => {
        if (res.code == 200) {
          this.roleInfo = res.list;
          this.roleInfo.memus = res.list.menus.split(",");
        }
      });
    },
    // 表单提交
    submitForm(formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {
          this.roleInfo.menus = this.$refs.tree.getCheckedKeys().join(",");
          this.$http
            .post(`/api/roleedit`, { ...this.roleInfo, id: this.roleId })
            .then(res => {
              if (res.code == 200) {
                return this.$success("操作成功");
              }
              this.$error("操作失败");
            });
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    }
  },
  created() {
    this.getMenuTree();
    this.getRoleInfo();
  }
};
</script>

<style>
</style>